package socketTest;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client_s {
    //定义一个标识符
    private Socket socket;
    public Client_s(){
        try {
            System.out.println("正在连接服务端");
            //连接服务端，给上ip地址以及端口号
            socket = new Socket("localhost",8105);
            System.out.println("已连接服务端");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();
            //以socket获取一个输出流(字节流)，socket是把信息发送到服务端的桥梁
            OutputStream os = socket.getOutputStream();
            //转换流(字节转换为字符)
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            //缓冲流
            BufferedWriter bw = new BufferedWriter(osw);
            //向文本输出流
            PrintWriter pw = new PrintWriter(bw,true);
            //定义一个扫描器，录入数据
            Scanner sc = new Scanner(System.in);
            String s = null;
            while (true){
                //录入的数据返回到s(标识符)上
                s = sc.nextLine();
                if("exit".equals(s)){//判定exit不等于s(标识符)
                    //跳出循坏
                    break;
                }
                //以行的形式输出每句字符串
                pw.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
        //本类实例化
        Client_s client_s = new Client_s();
        //执行实例化中的方法
        client_s.start();
    }
    //创建一个内部类，用来接收服务端的信息
    class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine())!=null){
                    System.out.println(message);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
